<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: {2021/5/22}
 * Time: {20:37}
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\model\mysql;


use app\common\lib\Status;
use think\Model;

class BaseModel extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 根据id更新数据
     * @param int $id
     * @param array $data
     * @return BaseModel|false
     */
    public function updateById(int $id = 0, array $data = [])
    {
        if (empty($id) || empty($data) || !is_array($data)) {
            return false;
        }
        //dump($data);exit();
        return $this->where('id', $id)
            ->save($data);
    }

    /**
     * @param array $data
     * @return bool
     */
    public function add(array $data): bool
    {
        if (empty($data)) {
            return false;
        }
        return $this->save($data);
    }

    /**
     * @param array $data
     * @return int|string
     */
    public function addById(array $data)
    {
        return $this->insertGetId($data);
    }

    /**
     * 根据条件获取分页
     * @param array $where
     * @param int $limit
     * @param string $order
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getIndexPage(array $where = [], int $limit = 10, string $order = 'id desc')
    {
        return $this->where($where)
            ->order($order)
            ->paginate($limit)
            ->toArray();
    }

    /**
     * 根据条件获取所有
     * @param array $where
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBaseByWherePage(array $where = [], string $field = '*')
    {
        return $this->field($field)
            ->where($where)
            ->select()
            ->toArray();
    }

    /**
     *
     * @param array $map
     * @return array|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBaseRepeat(array $map = [])
    {
        return $this->where($map)
            ->where('status', '<>', Status::Mysql_delete)
            ->find();
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function insertDataByInsertId(array $data = [])
    {
        $this->save($data);
        return $this->id;
    }

    /**
     * @param array $data
     * @return \think\Collection
     * @throws \Exception
     */
    public function addAll(array $data = [])
    {
        return $this->saveAll($data);
    }

}